import org.apache.http.HttpHost;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class ElasticsearchUploadExample {
    public static void main(String[] args) throws IOException {
        // 初始化Elasticsearch客户端
        RestClientBuilder builder = RestClient.builder(new HttpHost("localhost", 9200, "http"));
        RestHighLevelClient client = new RestHighLevelClient(builder);

        // 图片路径
        String imagePath = "C:\\Users\\Admin\\Desktop\\11\\3157269.png";
        // 将图片转换为字节数据
        byte[] imageData = Files.readAllBytes(Paths.get(imagePath));
        // 将字节数据转换为Base64字符串
        String base64Image = Base64.getEncoder().encodeToString(imageData);

        // 创建索引请求
        IndexRequest request = new IndexRequest("imgstore"); // 你的索引名
        request.id(System.currentTimeMillis()+""); // 文档ID
//        request.source("blob", base64Image, XContentType.JSON); // 图片字段名称和Base64字符串
        request.source("name", System.currentTimeMillis()+"");
        request.source("blob", base64Image); // 图片字段名称和Base64字符串
        // 发送请求并获取响应
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);

        // 输出结果
        System.out.println("Index response status: " + response.getResult());

        // 关闭客户端
        client.close();
    }
}
